﻿
Partial Class WebForm_ManageRoleUserMappingByUser_AssignUser
    Inherits My.MyUserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Me.BindDDLOrganization()
            Me.BindDDLUserType()
            RaiseEvent Loaded(Me, New EventArgs)
        End If
    End Sub

    Protected Sub gv_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gv.PageIndexChanging
        Me.gv.PageIndex = e.NewPageIndex
        Me.BindGV()
    End Sub

    Protected Sub gv_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv.RowCommand

        If e.CommandName = "btnAddUser" Then
            Dim row As GridViewRow = TryCast(TryCast(e.CommandSource, Control).NamingContainer, GridViewRow)
            Dim key As DataKey = Me.gv.DataKeys(row.RowIndex)

            Me.SelectedRowIndex = row.RowIndex
            Me.SearchUserControl1.ShowByRoleID(key("RoleID"))
        End If
    End Sub

    Protected Sub gv_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gv.RowDeleting
        If Me.DeleteData(e.RowIndex) = True Then
            Me.BindGV()
        End If
    End Sub

    Protected Sub gv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gv.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim key As DataKey = Me.gv.DataKeys(e.Row.RowIndex)

            Dim isRole As Boolean = TypeOf key("UserID") Is DBNull

            If isRole = False Then
                e.Row.BackColor = Me.gv.AlternatingRowStyle.BackColor
                TryCast(e.Row.FindControl("MultiView1"), MultiView).SetActiveView(TryCast(e.Row.FindControl("DeleteButtonView"), View))

                'If TypeOf DataBinder.Eval(e.Row.DataItem, "RoleParent") Is DBNull Then
                '    TryCast(e.Row.FindControl("btnDeleteUser"), Button).Enabled = False
                'End If
            Else
                e.Row.BackColor = Me.gv.RowStyle.BackColor
                e.Row.Font.Bold = True
                TryCast(e.Row.FindControl("MultiView1"), MultiView).SetActiveView(TryCast(e.Row.FindControl("AddButtonView"), View))
            End If
        End If
    End Sub

    'Protected Sub gv_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gv.SelectedIndexChanged
    '    Dim row As GridViewRow = Me.gv.SelectedRow
    '    Dim key As DataKey = Me.gv.DataKeys(row.RowIndex)

    '    If Me.DataAccessMode = My.DataAccessMode.Update Then
    '        Me.SearchRoleUserMappingByRole1.Show(key("RoleID"), Me)
    '    Else
    '        Me.SearchRoleUserMappingByRole1.ShowReadOnly(key("RoleID"))
    '    End If
    'End Sub

    'Protected Sub gv_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gv.Sorting
    '    Me.BindGV()
    'End Sub

    Protected Sub SearchUserControl1_Saving(ByVal sender As Object, ByVal e As System.EventArgs) Handles SearchUserControl1.Saving
        Me.SaveData(Me.SelectedRowIndex)
        Me.BindGV()
    End Sub

    Protected Sub btnQuery_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnQuery.Click
        Me.BindGV()
    End Sub
End Class

Partial Class WebForm_ManageRoleUserMappingByUser_AssignUser
    Public Sub Show()
        Me.DataAccessMode = My.DataAccessMode.Update
        'Me.BindGV()
    End Sub

    Public Sub ShowReadOnly()
        Me.DataAccessMode = My.DataAccessMode.Read
        'Me.BindGV()
    End Sub

    Private Sub BindDDLOrganization()
        Me.ddlOrganization.DataTextField = "OrganizationName"
        Me.ddlOrganization.DataValueField = "UOrganizationID"
        Me.ddlOrganization.DataSource = clsAuth.GetDDLDirectOrganizationData()
        Me.ddlOrganization.DataBind()

    End Sub

    Private Sub BindDDLUserType()
        Dim sql As New MyStringBuilder
        Dim dat As New clsData

        sql.AppendFormat("select * from Role ")
        sql.AppendFormat("where Virtual='N' ")
        sql.AppendFormat("and Active='Y' ")
        sql.AppendFormat("and RoleName<>'' ")
        sql.AppendFormat("order by RoleName ")

        Me.ddlUserType.DataTextField = "RoleName"
        Me.ddlUserType.DataValueField = "RoleID"
        Me.ddlUserType.DataSource = dat.GetData(sql)
        'Me.ddlUserType.DataTextField = "Text"
        'Me.ddlUserType.DataValueField = "Value"
        'Me.ddlUserType.DataSource = MyObj.GetCodeMappingData("User", "UserType")
        Me.ddlUserType.DataBind()

        Me.ddlUserType.Items.Insert(0, MyObj.GetDDLSelectAllItem())

    End Sub

    Private Sub BindGV()
        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        'sql.AppendFormat("select a.* ")
        'sql.AppendFormat("from ( ")

        '父群組之成員可修改子群組權限
        sql.AppendFormat("select r.RoleID, null as UserID, r.RoleName, null as UserName, r.RoleDescription ")
        sql.AppendFormat(", r_parent.RoleName as ParentRoleName ")
        sql.AppendFormat("from Role r ")
        sql.AppendFormat("left join Role r_parent on r.Parent = r_parent.RoleID ")

        '系統管理者可修改系統管理群組
        If clsAuth.IsAdministrator() = True Then
            sql.AppendFormat("where (r_parent.RoleID in ({0}) or r.Parent is null) ", clsAuth.GetRoleList())
        Else
            sql.AppendFormat("where r_parent.RoleID in ({0}) ", clsAuth.GetRoleList())
        End If

        sql.AppendFormat("and r.Active = 'Y' ")
        sql.AppendFormat("and r.Virtual = 'N' ")
        '只帶出查詢角色的項目
        If Me.ddlUserType.SelectedValue <> "" Then
            sql.AppendFormat("and r.RoleID = '{0}' ", Me.ddlUserType.SelectedValue)
        End If
        sql.AppendFormat("union ")
        sql.AppendFormat("select r.RoleID, u.UserID, r.RoleName, u.UserID + ' ' + u.UserName as UserName, '' as RoleDescription ")
        sql.AppendFormat(", r_parent.RoleName as ParentRoleName ")
        sql.AppendFormat("from RoleUserMappingView ru ")
        sql.AppendFormat("inner join GetUserByURoot('{0}') u on ru.UserID = u.UserID ", Me.ddlOrganization.SelectedValue)
        sql.AppendFormat("inner join Role r on ru.RoleID = r.RoleID ")
        sql.AppendFormat("left join Role r_parent on r.Parent = r_parent.RoleID ")

        '系統管理者可修改系統管理群組
        If clsAuth.IsAdministrator() = True Then
            sql.AppendFormat("where (r_parent.RoleID in ({0}) or r.Parent is null) ", clsAuth.GetRoleList())
        Else
            sql.AppendFormat("where r_parent.RoleID in ({0}) ", clsAuth.GetRoleList())
        End If

        sql.AppendFormat(Me.GetWhereSQL())


        sql.AppendFormat("order by r.RoleID, u.UserID ")

       ' MyObj.WriteLog(sql.ToString())
        Me.gv.DataSource = dat.GetData(sql)
        Me.gv.DataBind()

        If Me.DataAccessMode = My.DataAccessMode.Read Then
            Me.gv.Columns(4).Visible = False
        End If
    End Sub

    Private Function GetWhereSQL() As String
        Dim sql As New MyStringBuilder

        'If Me.ddlOrganization.SelectedValue <> "" Then
        '    sql.AppendFormat("and ot.URoot = '{0}' ", Me.ddlOrganization.SelectedValue)
        'End If

        'If Me.ddlUserType.SelectedValue <> "" Then
        '    sql.AppendFormat("and u.UserType = '{0}' ", Me.ddlUserType.SelectedValue)
        'End If
        If Me.ddlUserType.SelectedValue <> "" Then
            sql.AppendFormat("and r.RoleID = '{0}' ", Me.ddlUserType.SelectedValue)
        End If
 
        If Me.txtUserID.Text <> "" Then
            sql.AppendFormat("and u.UserID like '%{0}%' ", Me.txtUserID.Text.Replace("'", "''"))
        End If

        If Me.txtUserName.Text <> "" Then
            sql.AppendFormat("and u.UserName like '%{0}%' ", Me.txtUserName.Text.Replace("'", "''"))
        End If

        Return sql.ToString()
    End Function

    Private Function SaveData(ByVal rowIndex As Integer) As Boolean
        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        Dim row As GridViewRow = Me.gv.Rows(rowIndex)
        Dim key As DataKey = Me.gv.DataKeys(rowIndex)

        Using scope As New Transactions.TransactionScope
            For Each userID As String In Me.SearchUserControl1.SelectedUserList
                sql.Length = 0
                sql.AppendFormat("insert RoleUserMapping (RoleID, UserID) select ")
                sql.AppendFormat(" '{0}' ", key("RoleID"))
                sql.AppendFormat(",'{0}' ", userID)

                dat.AccData(sql.ToString(), Nothing, Data.CommandType.Text)
            Next
            scope.Complete()
        End Using

        Return True
    End Function

    Private Function DeleteData(ByVal rowIndex As Integer) As Boolean
        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        Dim row As GridViewRow = Me.gv.Rows(rowIndex)
        Dim key As DataKey = Me.gv.DataKeys(rowIndex)

        Using scope As New Transactions.TransactionScope
            sql.Length = 0
            sql.AppendFormat("delete RoleUserMapping where ")
            sql.AppendFormat(" RoleID='{0}' ", key("RoleID"))
            sql.AppendFormat("and UserID='{0}' ", key("UserID"))

            dat.AccData(sql.ToString(), Nothing, Data.CommandType.Text)
            scope.Complete()
        End Using

        Return True
    End Function

    Public Event Loaded(ByVal source As Object, ByVal e As EventArgs)

    Private Property SelectedRowIndex() As Integer
        Get
            Return ViewState("SelectedRowIndex")
        End Get
        Set(ByVal value As Integer)
            ViewState("SelectedRowIndex") = value
        End Set
    End Property

    Public Property DataAccessMode() As My.DataAccessMode
        Get
            If ViewState("DataAccessMode") Is Nothing Then
                Return My.DataAccessMode.Update
            End If

            Return ViewState("DataAccessMode")
        End Get
        Set(ByVal value As My.DataAccessMode)
            ViewState("DataAccessMode") = value
        End Set
    End Property
End Class